package com.hardy.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Author: Hardy
 * Date:   2020/9/22
 * Description:
 **/
public class ThreadMain {

    public static void main(String[] args) {

        syncTest();
    }

    // 线程池测试
    private static void threadTest() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 2,
                60L, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(2));


        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException ignored) {
                }
                System.out.println("--1--");
            });
        }
    }

    // AQS
    private static void lockTest() {
        ReentrantLock lock = new ReentrantLock();
        final Condition cond = lock.newCondition();

        new Thread(() -> {
            try {
                lock.lock();
                System.out.println("-- 1 --");
                cond.await();
                System.out.println("-- 2 --");
                lock.unlock();
            } catch (InterruptedException ignored) {
            }
        }).start();

        new Thread(() -> {
            try {
                lock.lock();
                System.out.println("-- 3 --");
                TimeUnit.SECONDS.sleep(5);
                System.out.println("-- 4 --");
                cond.signal();
                lock.unlock();
            } catch (InterruptedException ignored) {
            }
        }).start();
    }

    // AQS
    private static void syncTest() {
        ReentrantLock lock = new ReentrantLock();

        new Thread(() -> {
            try {
                synchronized (lock) {
                    System.out.println("-- 1 --");
                    lock.wait();
                    System.out.println("-- 2 --");
                }
            } catch (InterruptedException ignored) {
            }
        }).start();

        new Thread(() -> {
            try {
                synchronized (lock) {
                    System.out.println("-- 3 --");
                    TimeUnit.SECONDS.sleep(5);
                    lock.notify();
                    System.out.println("-- 4 --");
                }
            } catch (InterruptedException ignored) {
            }
        }).start();
    }

    // compiler
    private static void javacTest() {
    }
}
